package amushen.module;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import amushen.base.BaseBO;
import amushen.base.DBUtil;

public class Customer extends BaseBO {

	public Object query(Map paras, String user, InputStream is,
			DBUtil db) {
		List list=db.query("Customer.query", null);
		String[] head=new String[]{"id","name","contact_person","mobile","phone","email","im",
				"bank","account","cnt","sum1"
		};
		JSONArray arr=new JSONArray();
		JSONObject obj;
		Object[] row;
		for(int i=0;i<list.size();i++){
			row=(Object[])list.get(i);
			obj=new JSONObject();
			try {
				for(int j=0;j<head.length;j++){
						obj.put(head[j], row[j]);
				}
				if(row[10]==null){
					obj.put("cnt", "");
				}
			} catch (JSONException e) {
				e.printStackTrace();
				return "";
			}
			arr.put(obj);
		}		
		return arr.toString();
	}
	
	/**
	 * query id and name for combox
	 * @param paras
	 * @param user
	 * @param is
	 * @param db
	 * @return
	 */
	public Object queryComb(Map paras, String user, InputStream is,
			DBUtil db) {
		List list=db.query("Customer.query", null);
		String[] head=new String[]{"data","label"};
		JSONArray arr=new JSONArray();
		JSONObject obj;
		Object[] row;
		for(int i=0;i<list.size();i++){
			row=(Object[])list.get(i);
			obj=new JSONObject();
			try {
				for(int j=0;j<head.length;j++){
						obj.put(head[j], row[j]);
				}				
			} catch (JSONException e) {
				e.printStackTrace();
				return "";
			}
			arr.put(obj);
		}		
		return arr.toString();
	}
	
	
	public Object deleteCustomer(Map paras, String user, InputStream is,
			DBUtil db) {
		String id_s=(String)paras.get("id");
		Integer id=new Integer(id_s);
		if(db.update("Customer.delete", new Object[]{id})==-1){
			db.rollback();
			return "Failed to delete Customer";
		}
		db.commit();
		return "Success";
	}
	
	public Object insertCustomer(Map paras, String user, InputStream is,
			DBUtil db) {
		String name=getS((String)paras.get("name"));
		String contact_person=getS((String)paras.get("contact_person"));
		String mobile=(String)paras.get("mobile");
		String phone=(String)paras.get("phone");
		String email=(String)paras.get("email");
		String bank=getS((String)paras.get("bank"));
		String account=getS((String)paras.get("account"));
		String userId=(String)getSession().getAttribute("UserId");
		
		int ret=db.update("Customer.insert", new Object[]{name,contact_person,mobile,phone,email,"",bank,account,userId});
		if(ret==-1){
			db.rollback();
			return "Failed to insert Customer";
		}
		db.commit();
		return "Success";
	}
}
